import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import getPageTitle from '@/utils/get-page-title'
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  // console.log(to.path, '去哪里')
  // console.log(from.path, '从哪里来')
  NProgress.start() // 开启进度条
  const token = store.state.user.token
  if (token) {
    // 已经登陆了
    if (to.path === '/login') {
      // console.log('已经登陆了，不能再去登录页,跳转到首页')
      next('/')
      NProgress.done()
    } else {
      // console.log('已经登陆不是去登录页，放行')
      // 调用actions中函数，获取用户信息存储到vuex中
      if (!store.state.user.userInfo.userId) {
        await store.dispatch('user/setUserInfo')
      }
      next()
    }
  } else {
    // 没有登陆
    // 是否白名单， 不需要token || /404
    if (whiteList.includes(to.path)) {
      console.log('白名单,放行')
      next()
    } else {
      console.log('没有登陆，没有白名单，跳转登录页')
      next('/login')
      NProgress.done()
    }
  }
})

// 页面跳转完成会经过这里
router.afterEach(() => {
  NProgress.done()
})
